/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.dc.task;

import com.cxhd.dc.DataCache;
import com.cxhd.dc.DataConfig;
import com.cxhd.dc.tool.FileUtil;
import com.cxhd.dc.tool.HttpClientUt;
import com.cxhd.dc.tool.Tools;
import com.cxhd.dc.tool.ZipFileTool;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.dicom4j.dicom.DicomException;
import org.dicom4j.dicom.DicomTags;
import org.dicom4j.io.media.DicomFile;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 *
 * @author Administrator
 */
public class UnzipTaskQueue implements Runnable {

    private boolean start = true;
    private BlockingQueue unzipQueue;

    private DataCache dataCache;

    private static final org.apache.log4j.Logger logger1 = org.apache.log4j.Logger.getLogger("FileToZip");

    public UnzipTaskQueue(BlockingQueue unzipQueue) {
        this.unzipQueue = unzipQueue;
        dataCache = DataCache.getInstance();
    }

    @Override
    public void run() {
        while (true) {
            try {
                File file = (File) unzipQueue.take();
                unzip(file);
            } catch (Exception e) {
            }
        }
    }

    public void unzip(File file) {
        if (file.exists()) {
            // System.out.println(file.getName().substring(0, file.getName().lastIndexOf(".")) + "==" + FileUtil.makePSWD(file.getName().substring(0, file.getName().lastIndexOf("."))));
            try {
                System.out.println("解压文件-------------");
                File[] flist = ZipFileTool.UnZip(file.getAbsolutePath(), FileUtil.makePSWD(file.getName().substring(0, file.getName().lastIndexOf("."))));

                System.out.println(flist.length);
                if (flist != null && flist.length > 0) {
                    boolean deleteflag = checkFileType(flist, (file.getName().split("_")[2]).replace(".f", ""));
                    if (deleteflag) {
                        file.delete();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("文件已经处理");
        }
    }

    public boolean checkFileType(File[] files, String targetSn) {

        for (File f : files) {
            try {
                if ("center".equalsIgnoreCase(PropKit.get("serverType"))) {
                    String sendPacsPath = DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getDicomSendFolder() + "/";
                    sendPacsPath += targetSn + "/";
                    File f_sendPacsPath = new File(sendPacsPath);
                    if (!f_sendPacsPath.exists()) {
                        f_sendPacsPath.mkdirs();
                    }
                    Files.move(f, new File(sendPacsPath + f.getName()));
                } else //处理dcm文件
                 if (f.getName().endsWith(".dcm")) {
                     parseDicom(f.getAbsolutePath(), targetSn);//解析dicom
                        String sendPacsPath = DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getDicomSendFolder() + "/";
                        sendPacsPath += targetSn + "/";
                        File f_sendPacsPath = new File(sendPacsPath);
                        if (!f_sendPacsPath.exists()) {
                            f_sendPacsPath.mkdirs();
                        }

                        Files.move(f, new File(sendPacsPath + f.getName()));

                    } //处理xml文件
                    else if (f.getName().endsWith(".xml")) {
                        handlerXml(f, targetSn);
                    } //处理sql文件
                    else if (f.getName().endsWith(".sql")) {
                        String sqls[] = FileUtil.outWriter(f.getAbsolutePath()).split("`;`");
                        for (String sql : sqls) {
                            //  System.out.println(sql + "-------------------");
                            try {
                                Db.use("dcmris_en").update(sql);
                            } catch (Exception e) {
                                e.printStackTrace();
                                logger1.error(e);
                            }
                        }
                        Files.move(f, new File(DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getRecviceSqlFolder() + f.getName()));

                    } //处理rpt文件
                    else if (f.getName().endsWith(".rpt")) {
                        String[] infos = f.getName().replaceFirst("-", "_").replaceFirst("-", "_").split("_");

                        File dir = new File("k:/reports/" + infos[1] + "/");
                        if (!dir.exists() || !dir.isDirectory()) {
                            dir.mkdirs();
                        }
                        File newRptFile = new File("k:/reports/" + infos[1] + "/" + infos[2]);
                        if (newRptFile.exists()) {
                            newRptFile.delete();
                        }
                        Files.move(f, newRptFile);
                    } else if (f.getName().endsWith(".msg")) {
                        handlerMsg(f);
                    } else if (f.getName().endsWith(".mp4")) {
                        File dir = new File("k:/reports/mp4/");
                        if (!dir.exists()) {
                            dir.mkdirs();
                        }
                        Files.move(f, new File(dir.getAbsolutePath() + "/" + f.getName()));

                    } else if (f.getName().endsWith(".wav")) {
                        File dir = new File("k:/reports/wav/");
                        if (!dir.exists()) {
                            dir.mkdirs();
                        }
                        Files.move(f, new File(dir.getAbsolutePath() + "/" + f.getName()));

                    } else if (f.getName().endsWith(".wli")) {
                        String wliPath = DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getWliFolder();
                        String newWliPath = wliPath + f.getName().replace(".wli", ".xml");
                        Files.move(f, new File(newWliPath));

                        sendMwl("java -jar c:/cxhd2015/dcmPacs01/server-2.17.1/bin/editmwl.jar -a -f " + newWliPath + " -u jnp://localhost:31099");

                    }

            } catch (Exception ex) {
                ex.printStackTrace();
                System.out.println("移动文件错误");
                return false;
            }

        }
        return true;
    }

    private void handlerXml(File xml, String targetSn) {

//        try {
//            SAXReader reader = new SAXReader();
//            //读取文件 转换成Document
//            Document document = reader.read(xml);
//            //获取根节点元素对象
//            Element root = document.getRootElement();
//            Element data_set = root.element("data-set");
//            List<Element> elements = data_set.elements("element");
//           
//            //移动文件去其他文件夹
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            logger1.error(ex);
//        }
        try {
            Files.move(xml, new File(DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getRecviceXmlFolder() + xml.getName()));
        } catch (IOException ex) {

        }

    }

    private void parseDicom(String path,String targetSn) {

        DicomFile ldcm = new DicomFile(path);
        Map<String, String> patientInfo = new HashMap<String, String>();
        String studyIuid = null, pat_name = null, pat_id = null, modality = null, hospital = null;
        try {
            ldcm.open();
            studyIuid = ldcm.getDataset().getElement(DicomTags.StudyInstanceUID).getSingleStringValue();
            patientInfo.put("studyIuid", studyIuid);
            pat_name = ldcm.getDataset().getElement(DicomTags.PatientName).getSingleStringValue();
            patientInfo.put("pat_name", pat_name);
            pat_id = ldcm.getDataset().getElement(DicomTags.PatientID).getSingleStringValue();
            patientInfo.put("pat_id", pat_id);
            hospital = ldcm.getDataset().getElement(DicomTags.InstitutionName).getSingleStringValue();
            modality = ldcm.getDataset().getElement(DicomTags.Modality).getSingleStringValue();
            patientInfo.put("modality", modality);
            patientInfo.put("pat_birth", ldcm.getDataset().getElement(DicomTags.PatientBirthDate).getSingleStringValue());
            patientInfo.put("pat_sex", ldcm.getDataset().getElement(DicomTags.PatientSex).getSingleStringValue());
            patientInfo.put("pat_age", ldcm.getDataset().getElement(DicomTags.PatientAge).getSingleStringValue());
            System.out.println("解析dicom 成功"+patientInfo.toString());

        } catch (Exception ex) {

        } finally {
            try {
                ldcm.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (DicomException ex) {
                ex.printStackTrace();
            }
        }
        
        try{
            
             Record rc = Db.use("dcmris_en").findFirst("select * from logstudy where study_iuid='" + studyIuid + "'");
        if (rc == null || rc.getStr("study_iuid") == null) {

            logger1.info("send notice____________________________________");
            sendMessage(targetSn, hospital, pat_name, modality, patientInfo);
            long time = new File(path).lastModified();
            //获取文件的创建时间
            String ctime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(time));
            //保存到数据库
            // dataCache.setStudyMap(studyIuid, "1");

            Db.use("dcmris_en").update("insert into logstudy (from_sn,study_iuid,pat_id,pat_name,modality,createtime,file_starttime,other1)values(?,?,?,?,?,?,?,?)", targetSn, studyIuid, pat_id, pat_name, modality, Tools.getDateEN(), ctime, hospital);

            // dataCache.setStudyMap(studyIuid, "1");
            //保存Properties
            createProperties(DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getLogStudyFolder() + studyIuid + ".properties", pat_id, pat_name, modality);
            //发送消息

        } else {
            //更新同一个study最后收到的时间
            System.out.println("更新pro********************************");
            updateProperties(DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getLogStudyFolder() + studyIuid + ".properties");
        }
        }catch(Exception e){
        
        
        }


       

    }

    private void createProperties(String path, String pat_id, String pat_name, String modality) {

        Properties prop = new Properties();
        prop.put("pat_id", pat_id);
        prop.put("pat_name", pat_name);
        prop.put("modality", modality);
        prop.put("update", Tools.getDateEN());
        try {
            //保存
            FileOutputStream out = new FileOutputStream(path);

            prop.store(out, "the properties's comment");
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void updateProperties(String path) {

        Properties prop = new Properties();

        try {
            //保存
            OutputStream fos = new FileOutputStream(path);
            prop.setProperty("update", Tools.getDateEN());

            prop.store(fos, "the properties's comment");
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void sendMessage(String targetSn, String hospital, String pat_name, String modality, Map<String, String> patientInfo) {
        try {
            if (DataConfig.getInstance().isSendMessageFlag()) {
                String content = "来自[" + hospital + "] 的 （" + pat_name + "）检查类型：" + modality + "  请在2分钟后查收！";
                String hos = FileUtil.getSNtoHospitalName(targetSn);
                if (hos == null) {
                    hos = hospital;
                }
                content = "【" + pat_name + "】 的" + modality + "检查已到达中心，请查阅（" + hos + "）";
                String groupId = DataConfig.getInstance().getGroupId();
                String serverUrl = DataConfig.getInstance().getMessageServer();

                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("groupId", groupId));
                params.add(new BasicNameValuePair("contact", content));
                params.add(new BasicNameValuePair("patientInfo", new Gson().toJson(patientInfo)));
                params.add(new BasicNameValuePair("from", "影像中心"));
                logger1.info("http://" + serverUrl + "/app/message/sendGroupMessage.data" + patientInfo);
                String returnMsg = HttpClientUt.httpPost("http://" + serverUrl + "/app/message/sendGroupMessage.data", params);
                System.out.println("是否发送成功");
            }
        } catch (Exception e) {
            logger1.error(e);
            e.printStackTrace();
        }
    }

    private void handlerMsg(File f) {
        try {
            SAXReader reader = new SAXReader();
            //读取文件 转换成Document
            Document document = reader.read(f);
            //获取根节点元素对象
            Element root = document.getRootElement();
            Element path = root.element("path");
            Element detail = root.element("detail");
            String filePath = path.getText();
            if (filePath != null) {
                File fs = new File(filePath.substring(0, filePath.lastIndexOf("/") + 1));
                if (!fs.exists()) {
                    fs.mkdirs();
                }
                FileUtil.writeText(filePath, detail.getText());
                f.delete();
                //Files.move(f, new File(filePath));
            }
        } catch (Exception ex) {

        }
    }

    public void sendMwl(String cmd) {
        try {
            System.out.println("执行wli文件");
            Runtime r = Runtime.getRuntime();

            //  checkDevice(device, newFloder.getAbsolutePath());
            boolean flag = false;
            Process p = r.exec("cmd.exe /c " + cmd);
            System.out.println("cmd.exe /c " + cmd);
            //logger.info("cmd.exe /c C:\\dcmsyst\\tool-2.0.26\\bin\\dcmsnd -device " + device + " " + this.pacsInfo[2] + "@" + this.pacsInfo[0] + ":" + this.pacsInfo[1] + " " + newFloder.getAbsolutePath() + " -set 00080005= \"GB18030\" -set 00080080=\"" + ApProperties.getSNtoHospitalName(device) + "\"");
            //System.out.println("cmd.exe /c C:\\dcmsyst\\tool-2.0.26\\bin\\dcmsnd -device " + device + " " + this.pacsInfo[2] + "@" + this.pacsInfo[0] + ":" + this.pacsInfo[1] + " " + s.getAbsolutePath());
            //writeText("c:/dcmsyst/send.txt", "cmd.exe /c C:\\dcmsyst\\tool-2.0.26\\bin\\dcmsnd -device " + device + " " + this.pacsInfo[2] + "@" + this.pacsInfo[0] + ":" + this.pacsInfo[1] + " " + newFloder.getAbsolutePath());

            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String msg = null;
            while ((msg = br.readLine()) != null) {
                // logger1.info(msg);
                System.out.println("info msg : " + msg);
            }
            BufferedReader er = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            String error = null;
            while ((error = er.readLine()) != null) {
                // logger1.error(error);
                flag = true;

            }
            //p.waitFor();
            p.destroy();

        } catch (IOException ex) {

        }
    }

}
